package com.djsearch.ui;

import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONException;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.djsearch.R;
import com.djsearch.bean.GroupBuyGoods;
import com.djsearch.controller.AsyncHandler;
import com.djsearch.controller.IRequest;
import com.djsearch.controller.IResponse;
import com.djsearch.controller.JSONReq;
import com.djsearch.controller.JSONResp;
import com.djsearch.data.ImageManager;
import com.djsearch.data.RequestImage;
import com.djsearch.ui.GroupShopActivity.RequestParamStruct;
import com.djsearch.util.AsyncImageLoader;
import com.djsearch.util.AsyncImageLoader.ImageCallback;

/**
 * 团购商品详情页面
 * @author chenyang2
 *
 */
public class GroupShopDetailsActivity extends BaseActivity {
	
	private Context mContext;
	private Button backBtn;
	private GroupBuyGoods groupBuyGoods;
	private TextView describe,address,phoneNumText,
	personsBuyText,nowPriceText,oldPriceText;//商品描述,地址,电话,购买人数,现在价格（打折后价格）,原来价格
	private ImageView goodsImg;
	private AsyncImageLoader asyncImageLoader;
	private LinearLayout linearLayoutOne;
	private LinearLayout shouChangLayout,shareLayout,taoGouLayout;//收藏  分享 淘购
	private RelativeLayout phoneLayout;//电话布局
	private Button lookBtn,locationBtn;//去看看按钮,定位按钮
	private ProgressBar progressBar;
	private int width;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().requestFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.group_shop_details_layout);
		mContext = this;
		//接收从上个页面传递来的对象
		groupBuyGoods = (GroupBuyGoods) getIntent().getSerializableExtra("data"); 
		asyncImageLoader = new AsyncImageLoader("bigPic");
		//得到屏幕的分辨率
		getDisPlayMetrics();
		//初始化主界面
		initView();
		//初始化主界面相关点击事件
		initOnClick();
		//
		initHandler();
	}

	
	private Map<String, String> initRequestMap(GroupBuyGoods groupBuyGoods) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("userId", preferences.getString("userId", ""));//用户id
		map.put("name", groupBuyGoods.getShopName());//商品名字
		map.put("smallImage", groupBuyGoods.getSmallImage());//小图片
		map.put("bigImage", groupBuyGoods.getBigImage());//大图片
		map.put("place", groupBuyGoods.getShopPlace());//地点
		map.put("telephone", groupBuyGoods.getTelephone());//电话
		map.put("shopUrl", groupBuyGoods.getShopUrl());//商家地址
		map.put("description", groupBuyGoods.getShopDescripe());//描述
		
		return map;
	}
	
	
	@Override
	void initHandler() {
		// TODO Auto-generated method stub

	}

	@Override
	void initView() {
		// TODO Auto-generated method stub
		backBtn = (Button)findViewById(R.id.btnBack);
		locationBtn = (Button)findViewById(R.id.btndingwei);
		if (groupBuyGoods.getLatitude().equals("") || groupBuyGoods.getLongitude().equals("")) {
			locationBtn.setVisibility(View.GONE);
		}
		progressBar = (ProgressBar)findViewById(R.id.progressBar);
		linearLayoutOne = (LinearLayout)findViewById(R.id.linearLayoutOne);
		width = linearLayoutOne.getWidth();
		describe = (TextView)findViewById(R.id.describe);
		describe.setText(groupBuyGoods.getShopDescripe());
		goodsImg = (ImageView)findViewById(R.id.goodsImg);
		address = (TextView)findViewById(R.id.locationInfoText);
		address.setText(groupBuyGoods.getShopPlace());
		phoneNumText = (TextView)findViewById(R.id.phoneNumText);
		phoneNumText.setText(groupBuyGoods.getTelephone());
		personsBuyText = (TextView)findViewById(R.id.personsBuyText);
		personsBuyText.setText(Math.floor(Double.valueOf(groupBuyGoods.getHasShop()))+"人购买");
		nowPriceText = (TextView)findViewById(R.id.nowPriceText);
		nowPriceText.setText(groupBuyGoods.getSalePrice());
		oldPriceText = (TextView)findViewById(R.id.oldPriceText);
		oldPriceText.setText(groupBuyGoods.getShopPrice());
		lookBtn = (Button)findViewById(R.id.toLookBtn);
		shouChangLayout = (LinearLayout)findViewById(R.id.shouChangLayout);
		shareLayout = (LinearLayout)findViewById(R.id.shareLayout);
		taoGouLayout = (LinearLayout)findViewById(R.id.taoGouLayout);
        asyncImageLoader.loadDrawable(progressBar,goodsImg,groupBuyGoods.getBigImage(), new ImageCallback() {
			
			@Override
			public void imageLoaded(ProgressBar progressBar,ImageView imageView,Drawable imageDrawable, String imageUrl, String tag) {
				// TODO Auto-generated method stub
				goodsImg.setImageBitmap(ImageManager.drawableToBitmap(imageDrawable,464.0f));
				progressBar.setVisibility(View.GONE);
			}
		});
        
//        RequestImage.getIntance(null, "BigPic").download(groupBuyGoods.getBigImage(), 
//				goodsImg);

	}

	@Override
	void initOnClick() {
		// TODO Auto-generated method stub
		backBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
//			startActivity(mContext, GroupShopActivity.class, 1)	;
				finish();
			}
		});
		locationBtn.setOnClickListener(new View.OnClickListener() {
			//定位
			@Override
			public void onClick(View v) {
				double locInfo[] = new double[2];
				locInfo[0] = Double.parseDouble(groupBuyGoods.getLatitude());
				locInfo[1] = Double.parseDouble(groupBuyGoods.getLongitude());
				Intent intent = new Intent(mContext,LocInfoActivity.class);
				Bundle bundle = new Bundle();
				bundle.putDoubleArray("locinfo", locInfo);
				bundle.putString("type", "0");
				intent.putExtras(bundle);
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			}
		});
		shouChangLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!isLogin()) {
					Toast.makeText(mContext, "未登录，不能收藏", 5000).show();
				} else {
					//开始收藏
					if (groupBuyGoods != null) {
						requestShouChang(initRequestMap(groupBuyGoods));
					}
				}
			}

		});
		shareLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				//分享
//                share(groupBuyGoods.getShopDescripe()+":"+ groupBuyGoods.getShopUrl());
				Intent intent = new Intent(mContext,ShareToWeiboActivity.class);
//				intent.putExtra("shareContent", 
//						groupBuyGoods.getShopDescripe()+":"+ groupBuyGoods.getShopUrl());
				Bundle bundle = new Bundle();
				bundle.putString("shareContent", groupBuyGoods.getShopDescripe());
				bundle.putString("goodsUrl", groupBuyGoods.getShopUrl());
				intent.putExtras(bundle);
				startActivity(intent);
				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			}
		});
		taoGouLayout.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// 淘购
				startActivity(mContext, TaoGouActivity.class, 0);
			}
		});
		lookBtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				//去看看
				Intent intent=new Intent();
		        intent.setClass(GroupShopDetailsActivity.this, WebViewActivity.class);
		        Bundle bundle = new Bundle();
		        bundle.putString("url", groupBuyGoods.getShopUrl());
		        bundle.putString("whichBuyType", "groupShop");
		        intent.putExtras(bundle);
//		        intent.putExtra("url", groupBuyGoods.getShopUrl());
		        startActivity(intent);
		        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
			}
		});
	}

	/**
	 * 请求收藏
	 * data参数说明：{“userId”:”8765”,“name”:”大酒店”,”smallImage”:http://image.jpg,
       ”bigImage”:”http://image.jpg”,”place”:”地点”,
       ”telephone”:”0373-5678”,
       ”shopUrl”:http://www.baidu.com,”description”:”描述”}
	 */
	private void requestShouChang(Map<String, String> map) {

		IRequest request = new JSONReq("collect",map);
		HTTP.post(request, new AsyncHandler(){
			@Override
			public void onStart() {
				showDialog("正在收藏...");
			}
			@Override
			public void onSuccess(JSONResp response) {
				// TODO Auto-generated method stub
				int result = response.result();
				if(IResponse.Success==result){
						getDataToResolve(response);
				} else if (IResponse.Fail==result) {
					Toast.makeText(mContext, "收藏失败", 5000).show();
				}
					missDialog();
			}
			@Override
			public void onFailure(Throwable e, String response) {
				// TODO Auto-generated method stub
//				super.onFailure(e, response);
				missDialog();
//				Log.e("GROUP", response);
				Toast.makeText(mContext, response, 5000).show();
//				missProgressBar();
			}
			
		});
	
		
	}
	
	/**
	 * 点击返回键
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			startActivity(mContext, GroupShopActivity.class, 1);
		}
		return false;
	}

	@Override
	void getDataToResolve(JSONResp response) {
		// TODO Auto-generated method stub
		String resultMessage;
		try {
			resultMessage = response.getString("message");
			Toast.makeText(mContext, resultMessage, 5000).show();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
